import axios from 'axios';
import qs from 'qs';

axios.defaults.timeout = 5000;
axios.defaults.baseURL = '';


//http request 拦截器
axios.interceptors.request.use(config => {
	return config;
}, error => {
	return Promise.reject(err);
});


//http response 拦截器
axios.interceptors.response.use(response => {
	return response;
}, error => {
	return Promise.reject(error)
})

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, params = {}) {
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: params
		}).then(response => {
			resolve(response.data);
		}).catch(err => {
			reject(err)
		})
	})
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, params = {}, formdataFlag = false){
	if(formdataFlag) {
		return postformdata(url, params);
	}
	return new Promise((resolve,reject) => {
		axios.post(url, params).then(response => {
			resolve(response.data);
		}).catch(err => {
			reject(err)
		})
	})
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function postformdata(url, params = {}){
	return new Promise((resolve,reject) => {
		axios.post(url, qs.stringify(params)).then(response => {
			resolve(response.data);
		}).catch(err => {
			reject(err)
		})
	})
}

/**
 * 封装request请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function request(url, params = {}){
	let data = {
		url: url,
		params: params
	}

	return new Promise((resolve,reject) => {
		axios.request(data).then(response => {
			resolve(response.data);
		}).catch(err => {
			reject(err)
		})
	})
}


